package com.youlu.campus.website.service.impl;

import com.youlu.campus.website.entity.ContactMessage;
import com.youlu.campus.website.entity.ContactMessagePageQuery;
import com.youlu.campus.website.repositories.ContactMessageRepository;
import com.youlu.campus.website.service.ContactMessageService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

/**
 * 联系我们留言业务逻辑层实现类
 *
 * @author su
 * @date 2025/08/30
 */
@Service
public class ContactMessageServiceImpl implements ContactMessageService {

    @Autowired
    private ContactMessageRepository contactMessageRepository;

    @Resource(name = "websiteMongoTemplate")
    private MongoTemplate mongoTemplate;

    @Override
    public ContactMessage saveMessage(ContactMessage contactMessage) {
        Assert.notNull(contactMessage, "留言实体不能为 null");
        Assert.hasText(contactMessage.getContent(), "留言内容不能为空");
        Assert.hasText(contactMessage.getContactInfo(), "电话或邮箱不能为空");
        if (StringUtils.isNotBlank(contactMessage.getId())) {
            contactMessage.setUpdateTime(LocalDateTime.now());
        } else {
            contactMessage.setCreateTime(LocalDateTime.now());
        }
        ContactMessage savedMessage = contactMessageRepository.save(contactMessage);
        return savedMessage;

    }

    @Override
    public Boolean deleteMessageById(String id) {
        Assert.hasText(id, "留言 ID 不能为空");
        try {
            contactMessageRepository.deleteById(id);
            return Boolean.TRUE;
        } catch (Exception e) {
            return Boolean.FALSE;
        }
    }

    @Override
    public ContactMessage getMessageById(String id) {
        Assert.hasText(id, "留言 ID 不能为空");
        ContactMessage message = contactMessageRepository.findById(id).orElse(null);
        if (message == null) {
            return null;
        }
        return message;
    }

    @Override
    public Page<ContactMessage> findByPage(ContactMessagePageQuery pageQuery) {
        Query query = new Query();
        if (StringUtils.isNotBlank(pageQuery.getContactInfo())) {
            query.addCriteria(Criteria.where("contactInfo").regex(pageQuery.getContactInfo(), "i"));
        }
        //统计总条数（分页需要先查总数）
        long total = mongoTemplate.count(query, ContactMessage.class);

        Pageable pageRequest = PageRequest.of(pageQuery.getPage() - 1, pageQuery.getPageSize(), Sort.by("createTime").descending());
        List<ContactMessage> list;
        if (total == 0) {
            list = Arrays.asList();
        } else {
            // 应用分页（设置跳过的条数和查询的条数）
            query.skip(pageRequest.getOffset()).limit(pageRequest.getPageSize());
            // 应用排序
            query.with(pageRequest.getSort());
            list = mongoTemplate.find(query, ContactMessage.class);
        }
        return PageableExecutionUtils.getPage(list, pageRequest, () -> total);
    }


    @Override
    public List<ContactMessage> listAllMessages() {
        List<ContactMessage> messageList = contactMessageRepository.findAll();
        return messageList;
    }
}